package ace.module.oauth2.server.core.autoconfig.config;

import ace.cmp.openfeign.security.oauth2.core.config.FeignInternalServerOauth2SecurityConfig;
import ace.module.oauth2.server.core.impl.authentication.ace.Interceptor.Oauth2RestRequestInterceptorHolder;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.openfeign.security.OAuth2AccessTokenInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;

/**
 * @author caspar auto config oauth2 rest authentication
 */
@Slf4j
@AllArgsConstructor
@Configuration
public class Oauth2ServerRestAuthenticationConfig {

  @Bean
  @ConditionalOnMissingBean
  public Oauth2RestRequestInterceptorHolder oauth2RestRequestInterceptor(
      @Value("${spring.cloud.openfeign.oauth2.clientRegistrationId:}") String clientRegistrationId,
      ClientRegistrationRepository clientRegistrationRepository,
      OAuth2AuthorizedClientService oauth2AuthorizedClientService
  ) {

    OAuth2AuthorizedClientManager oauth2AuthorizedClientManager = FeignInternalServerOauth2SecurityConfig
        .getDefaultOauth2AuthorizedClientManagerInstance(clientRegistrationRepository, oauth2AuthorizedClientService);

    OAuth2AccessTokenInterceptor oauth2AccessTokenInterceptor = FeignInternalServerOauth2SecurityConfig
        .getDefaultOauth2AccessTokenInterceptorInstance(clientRegistrationId, oauth2AuthorizedClientManager);

    return new Oauth2RestRequestInterceptorHolder(oauth2AccessTokenInterceptor);
  }
}
